//
//  LoginViewController.m
//  SG
//
//  Created by FISH on 2018/4/19.
//  Copyright © 2018年 yimindai. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisteredViewController.h"
#import "ForgotPwordViewController.h"
@interface LoginViewController ()<YBAttributeTapActionDelegate,UITextFieldDelegate>

@end

@implementation LoginViewController

//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
//{
//   if(_mView1Text.text.length>11)
//   {
//       return NO;
//   }
//    return YES;
//}

-(void)checkAlertLab
{
    _show = YES;
    _mView3Btn.backgroundColor = KRedColor;
    [_intAbuted addAttribute:NSForegroundColorAttributeName value:KRedColor range:NSMakeRange(_mAlertLab.text.length-9, 9)];
    _mAlertLab.attributedText = _intAbuted;
}

-(void)uncheckAlertLab
{
    _show = NO;
    _mView3Btn.backgroundColor = KLightGrayColor;
    [_intAbuted addAttribute:NSForegroundColorAttributeName value:KLightGrayColor range:NSMakeRange(_mAlertLab.text.length-9, 9)];
    _mAlertLab.attributedText = _intAbuted;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField == _mView1Text) {
        [self uncheckAlertLab];
    }
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == _mView1Text) {
        if (string.length == 0)
        {
            [self uncheckAlertLab];
            return YES;
        }
        if(textField.text.length >= 10){
            [self checkAlertLab];
        }
        else{
            [self uncheckAlertLab];
        }
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength > 11) {
            
            return NO;
        }
    }
    return YES;
}

- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == _mView1Text) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;

    
    [self createLoginViewControllerUI];
}

-(void)createLoginViewControllerUI
{
    _bgImgView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight/3);
    
    [self createNaViewUI];
    
    [self createIconUI];
    
    [self createMainViewUI];
    
    [self createQuickLoginUI];
}

- (void)createNaViewUI
{
    _NaView.frame = CGRectMake(0, 0, kScreenWidth, kNavHeight);
    _leftBtn.frame = CGRectMake(10, kNavY+(44-30)/2, 30, 30);
    _rightBtn.frame = CGRectMake(kScreenWidth-40, kNavY+(44-30)/2, 30, 30);
    _contentLab.frame = CGRectMake(40, kNavY+(44-30)/2, kScreenWidth-80, 30);
    _leftBtn.titleLabel.font = FONTTWO;
    [_leftBtn addTarget:self action:@selector(toCancel) forControlEvents:UIControlEventTouchUpInside];
    _rightBtn.titleLabel.font = FONTTWO;
    [_rightBtn addTarget:self action:@selector(toRegistered) forControlEvents:UIControlEventTouchUpInside];
    _contentLab.font = FONTTHRE;
    _contentLab.text = @"登录搜缘";
}

- (void)createIconUI
{
#pragma ICON展示
    _iconImgView.frame = CGRectMake((kScreenWidth-kRealValue(60))/2, kNavHeight+kRealValue(20), kRealValue(60), kRealValue(60));
    _iconLab.frame = CGRectMake(0, _iconImgView.frame.origin.y+_iconImgView.frame.size.height+10, kScreenWidth, 21);
    _iconLab.font = FONTTWO;
}

-(void)createMainViewUI
{
    _mainView.frame = CGRectMake(0, _iconLab.frame.origin.y+_iconLab.frame.size.height+kRealValue(50), kScreenWidth, kScreenHeight-kRealValue(60)-_iconLab.frame.origin.y-_iconLab.frame.size.height-kRealValue(120));
    _mleftBtn.frame = CGRectMake(0, 0, kScreenWidth/2, 30);
    _mleftBtn.titleLabel.font = FONTTWO;
    _mleftBtn.titleLabel.textColor = KRedColor;
    [_mleftBtn addTarget:self action:@selector(toSelectLeft) forControlEvents:UIControlEventTouchUpInside];
    _mrightBtn.frame = CGRectMake(kScreenWidth/2, 0, kScreenWidth/2, 30);
    _mrightBtn.titleLabel.font = FONTTWO;
    _mrightBtn.titleLabel.textColor = KLightGrayColor;
    [_mrightBtn addTarget:self action:@selector(toSelectRight) forControlEvents:UIControlEventTouchUpInside];
    _mgrayView.frame = CGRectMake(0, _mrightBtn.frame.size.height, kScreenWidth, 1);
    _mredView.frame  = CGRectMake(0, _mrightBtn.frame.size.height, kScreenWidth/2, 1);
    _mView1.frame = CGRectMake(20, _mredView.frame.origin.y+30, kScreenWidth-40, 40);
    _mView1.layer.masksToBounds = YES;
    _mView1.layer.cornerRadius = 5;
    _mView1.layer.borderWidth = 1;
    _mView1.layer.borderColor = KLightGrayColor.CGColor;
    _mView1Img.frame = CGRectMake(10,(_mView1.frame.size.height-18)/2, 13, 18);
    _mView1Text.frame = CGRectMake(33, 0, _mView1.frame.size.width-33, _mView1.frame.size.height);
    _mView1Text.delegate = self;
    _mView1Text.placeholder = @"请输入手机号";
    _mView1Text.clearButtonMode = UITextFieldViewModeWhileEditing;
    _mView1Text.keyboardType = UIKeyboardTypeNumberPad;//键盘类型
    _mView1Text.font = FONTTWO;
    _mView2.frame = CGRectMake(20, _mredView.frame.origin.y+90, kScreenWidth-40, _mView1.frame.size.height);
    _mView2.layer.masksToBounds = YES;
    _mView2.layer.cornerRadius = 5;
    _mView2.layer.borderWidth = 1;
    _mView2.layer.borderColor = KLightGrayColor.CGColor;
    _mView2Img.frame = CGRectMake(10,(_mView1.frame.size.height-18)/2, 13, 18);
    _mView2Text.placeholder = @"请输入密码";
    _mView2Text.keyboardType = UIKeyboardTypeDefault;
    _mView2Text.font = FONTTWO;
    _mView2Text.frame = CGRectMake(33, 0, _mView2.frame.size.width-33-23, _mView2.frame.size.height);
    _mView2Btn.frame = CGRectMake(_mView2.frame.size.width-13-5, (_mView2.frame.size.height-18)/2, 13, 18);
    _mView2Btn.tag = 2000;
    _mView2Btn.titleLabel.font = FONTTWO;
    [_mView2Btn setTitle:@"X" forState:UIControlStateNormal];
    [_mView2Btn addTarget:self action:@selector(toChangeSecureTextEntry:) forControlEvents:UIControlEventTouchUpInside];
    _mView3.frame = CGRectMake(20, _mredView.frame.origin.y+90, kScreenWidth-40, _mView1.frame.size.height);
    _mView3.layer.masksToBounds = YES;
    _mView3.layer.cornerRadius = 5;
    _mView3.layer.borderWidth = 1;
    _mView3.layer.borderColor = KLightGrayColor.CGColor;
    _mView3Img.frame = CGRectMake(10,(_mView3.frame.size.height-18)/2, 13, 18);
    _mView3Text.placeholder = @"请输入验证码";
    _mView3Text.keyboardType = UIKeyboardTypeDefault;
    _mView3Text.font = FONTTWO;
    _mView3Text.frame = CGRectMake(33, 0, _mView3.frame.size.width-133, _mView3.frame.size.height);
    _mView3Btn.frame = CGRectMake(_mView3.frame.size.width-100, 0, 100, _mView3.frame.size.height);
    _mView3Btn.tag = 3000;
    _mView3Btn.titleLabel.font = FONTTWO;
    [_mView3Btn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_mView3Btn addTarget:self action:@selector(toChangeSecureTextEntry:) forControlEvents:UIControlEventTouchUpInside];
    _mView3Btn.backgroundColor = KLightGrayColor;
    [_mView3 setHidden:YES];
    NSString *intStr = @"短信验证码收不到?点此接收语音验证码";
    NSDictionary *intDic=@{NSFontAttributeName:FONTONE,NSForegroundColorAttributeName:KLightGrayColor};
    _intAbuted = [[NSMutableAttributedString alloc]initWithString:intStr attributes:intDic];
    [_intAbuted addAttribute:NSFontAttributeName value:FONTONE range:NSMakeRange(intStr.length-9, 9)];//变大
    [_intAbuted addAttribute:NSForegroundColorAttributeName value:KLightGrayColor range:NSMakeRange(intStr.length-9, 9)];
    CGSize labSize = [self sizeWithString:intStr font:FONTONE maxWidth:kScreenWidth];
    _mAlertLab.frame = CGRectMake(20,  _mView2.frame.origin.y+_mView2.frame.size.height+5, labSize.width, 21);
    _mAlertLab.attributedText = _intAbuted;
    [_mAlertLab yb_addAttributeTapActionWithStrings:@[@"点此接收语音验证码"] delegate:self];
    [_mAlertLab setHidden:YES];
    _mAlertLab.font = FONTONE;
    _mAlertBtn.frame = CGRectMake(kScreenWidth-80, _mAlertLab.frame.origin.y, 60, _mAlertLab.frame.size.height);
    _mAlertBtn.titleLabel.font = FONTONE;
    [_mAlertBtn addTarget:self action:@selector(toForgotPassword) forControlEvents:UIControlEventTouchUpInside];
    _loginBtn.frame = CGRectMake(20, _mAlertBtn.frame.origin.y+_mAlertBtn.frame.size.height+40, kScreenWidth-40, _mView1.frame.size.height);
    _loginBtn.titleLabel.font = FONTTHRE;
    [_loginBtn addTarget:self action:@selector(toSelectLogin) forControlEvents:UIControlEventTouchUpInside];
    
    [self createAttributeUI];
}

- (void)createAttributeUI
{
    NSString *intStr = @"登录或注册即表示同意遵守 《搜缘使用协议》";
    NSDictionary *intDic=@{NSFontAttributeName:FONTONE,NSForegroundColorAttributeName:KLightGrayColor};
    NSMutableAttributedString *intAbuted = [[NSMutableAttributedString alloc]initWithString:intStr attributes:intDic];
    [intAbuted addAttribute:NSFontAttributeName value:FONTONE range:NSMakeRange(intStr.length-8, 8)];//变大
    [intAbuted addAttribute:NSForegroundColorAttributeName value:KRedColor range:NSMakeRange(intStr.length-8, 8)];
    CGSize labSize = [self sizeWithString:intStr font:FONTONE maxWidth:kScreenWidth];
    int labelX = (kScreenWidth - labSize.width)/2;
    _loginLab.frame = CGRectMake(labelX,  kScreenWidth-30, labSize.width, 21);
    _loginLab.attributedText = intAbuted;
    [_loginLab yb_addAttributeTapActionWithStrings:@[@"《搜缘使用协议》"] delegate:self];
}

- (void)createQuickLoginUI
{
    NSArray *btnArray = @[@"微信",@"QQ"];
    _btnView.frame = CGRectMake(0, kScreenWidth-kRealValue(120), kScreenWidth, kRealValue(100));
    _promptLab.frame = CGRectMake((kScreenWidth-100)/2, 5, 100, 21);
    _promptLab.font = FONTTHRE;
    _leftView.frame = CGRectMake(10, 10, (kScreenWidth-120)/2, 1);
    _rightView.frame = CGRectMake(_promptLab.frame.origin.x+_promptLab.frame.size.width, 10, (kScreenWidth-120)/2, 1);
    
    int btnWidth = kRealValue(100)-36;
    int btnInterval = (kScreenWidth - btnArray.count*btnWidth)/(btnArray.count+1);
    for(int tag = 0;tag < btnArray.count;tag++)
    {
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(btnInterval*(tag+1)+btnWidth*tag, _promptLab.frame.origin.y+_promptLab.frame.size.height+10, btnWidth, btnWidth)];
        [btn setTitle:StringFormat(@"%@", btnArray[tag]) forState:UIControlStateNormal];
        btn.tag = tag;
        [btn addTarget:self action:@selector(toSelectInterface:) forControlEvents:UIControlEventTouchUpInside];
        btn.backgroundColor = KLightGrayColor;
        [_btnView addSubview:btn];
    }
}

- (void)toSelectInterface:(UIButton*)sender
{
    if(sender.tag == 0)
    {
        [self getAuthWithUserInfoFromWechat];
    }
    else if (sender.tag == 1)
    {
        [self getAuthWithUserInfoFromQQ];
    }
}

- (void)getAuthWithUserInfoFromQQ
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_QQ currentViewController:nil completion:^(id result, NSError *error) {
        if (error) {
            DLog(@"%@",error);
        } else {
            UMSocialUserInfoResponse *resp = result;
            
            // 授权信息
            DLog(@"QQ uid: %@", resp.uid);
            DLog(@"QQ openid: %@", resp.openid);
            DLog(@"QQ unionid: %@", resp.unionId);
            DLog(@"QQ accessToken: %@", resp.accessToken);
            DLog(@"QQ expiration: %@", resp.expiration);
            
            // 用户信息
            DLog(@"QQ name: %@", resp.name);
            DLog(@"QQ iconurl: %@", resp.iconurl);
            DLog(@"QQ gender: %@", resp.unionGender);
            
            // 第三方平台SDK源数据
            DLog(@"QQ originalResponse: %@", resp.originalResponse);
        }
    }];
}

- (void)getAuthWithUserInfoFromWechat
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:nil completion:^(id result, NSError *error) {
        if (error) {
            DLog(@"%@",error);
            
        } else {
            UMSocialUserInfoResponse *resp = result;
            
            // 授权信息
            DLog(@"Wechat uid: %@", resp.uid);
            DLog(@"Wechat openid: %@", resp.openid);
            DLog(@"Wechat unionid: %@", resp.unionId);
            DLog(@"Wechat accessToken: %@", resp.accessToken);
            DLog(@"Wechat refreshToken: %@", resp.refreshToken);
            DLog(@"Wechat expiration: %@", resp.expiration);
            
            // 用户信息
            DLog(@"Wechat name: %@", resp.name);
            DLog(@"Wechat iconurl: %@", resp.iconurl);
            DLog(@"Wechat gender: %@", resp.unionGender);
            
            // 第三方平台SDK源数据
            DLog(@"Wechat originalResponse: %@", resp.originalResponse);
        }
    }];
}

- (void)toSelectLeft
{
    [_mView2 setHidden:NO];
    [_mView3 setHidden:YES];
    _mleftBtn.titleLabel.textColor = KRedColor;
    _mrightBtn.titleLabel.textColor = KLightGrayColor;
    _mredView.frame  = CGRectMake(0, _mrightBtn.frame.size.height, kScreenWidth/2, 1);
    [_mAlertLab setHidden:YES];
    [_mAlertBtn setHidden:NO];
    _contentLab.text = @"登录搜缘";
}

- (void)toSelectRight
{
    [_mView2 setHidden:YES];
    [_mView3 setHidden:NO];
    _mleftBtn.titleLabel.textColor = KLightGrayColor;
    _mrightBtn.titleLabel.textColor = KRedColor;
    _mredView.frame  = CGRectMake(kScreenWidth/2, _mrightBtn.frame.size.height, kScreenWidth/2, 1);
    [_mAlertLab setHidden:NO];
    [_mAlertBtn setHidden:YES];
    _contentLab.text = @"手机快捷登录";
}

- (void)newThread
{
    for (NSInteger i = 0; i < 60; i++)
    {
        NSMutableDictionary *dicparam = [NSMutableDictionary dictionary];
        [dicparam setValue:[NSNumber numberWithInteger:60] forKey:@"KEY_COMMAND_ID"];
        [dicparam setValue:[NSString stringWithFormat:@"%@s",[NSNumber numberWithInteger:60 - i]] forKey:@"MESSAGE_VALUE"];
        [self performSelectorOnMainThread:@selector(ON_COMMAND2:) withObject:dicparam waitUntilDone:NO];
        [NSThread sleepForTimeInterval:1];
        if ([[NSThread currentThread] isCancelled])
        {
            [NSThread exit];
            return;
        }
    }
    NSMutableDictionary *dicparam = [NSMutableDictionary dictionary];
    [dicparam setValue:[NSNumber numberWithInteger:100] forKey:@"KEY_COMMAND_ID"];
    [self performSelectorOnMainThread:@selector(ON_COMMAND2:) withObject:dicparam waitUntilDone:NO];
}

- (void)ON_COMMAND2:(NSDictionary *)wParam
{//按钮上倒计时动画停止
    NSInteger nCmd = [[wParam valueForKey:@"KEY_COMMAND_ID"] integerValue];
    if (nCmd == 60)
    {
        [_mView3Btn setTitle:[wParam valueForKey:@"MESSAGE_VALUE"] forState:UIControlStateNormal];
        [_mView3Btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self uncheckAlertLab];
    }
    else if (nCmd ==100)
    {
        [_mView3Btn setEnabled:YES];//允许点击
        [_mView3Btn setTitle:@"获取验证码" forState:UIControlStateNormal];
        _mView3Btn.backgroundColor = KLightGrayColor;
        [self checkAlertLab];
    }
}

-(void)toChangeSecureTextEntry:(UIButton*)sender
{
    if(sender.tag == 2000)
    {
        _bChecked = !_bChecked;
        if (_bChecked == YES)
        {
            _mView2Btn.backgroundColor = KRedColor;
            _mView2Text.secureTextEntry = YES;
        }
        else
        {
            _mView2Btn.backgroundColor = KClearColor;
            _mView2Text.secureTextEntry = NO;
        }
    }
    else if (sender.tag == 3000)
    {
        NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread) object:nil];
        [thread start];
        [_mView3Btn setEnabled:NO];//不允许点击
        _mView3Btn.backgroundColor = KLightGrayColor;
    }

}

- (void)yb_attributeTapReturnString:(NSString *)string range:(NSRange)range index:(NSInteger)index
{
    if([string isEqualToString:@"点此接收语音验证码"])
    {
        if(_show == YES)
        {
            DLog(@"点此接收语音验证码");
        }
    }
    else if ([string isEqualToString:@"《搜缘使用协议》"])
    {
        DLog(@"《搜缘使用协议》");
    }
}

- (void)toSelectLogin
{
    DLog(@"立即登录");
}

- (void)toForgotPassword
{
    DLog(@"忘记密码");
    ForgotPwordViewController *ForgotPwordVC = [[ForgotPwordViewController alloc]init];
    [self.navigationController pushViewController:ForgotPwordVC animated:NO];
}

- (void)toRegistered
{
    DLog(@"注册");
    RegisteredViewController *RegisteredVC = [[RegisteredViewController alloc]init];
    [self.navigationController pushViewController:RegisteredVC animated:NO];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
